let isRefreshing = true; // 请求锁
let pendings = []; // 请求列表
const baseUrl = 'https://elf.byxfd.com' // 基础路径
const app = getApp()

const request = ({
  method,
  url,
  data,
  header,
  options = {
    needLogin: true
  }
}) => {
  const token = wx.getStorageSync('token')
  let myHeader = {}
  if (options.needLogin) {
    myHeader = {
      ...header,
      Authorization: token || ''
    }
  } else {
    myHeader = {
      ...header
    }
  }
  return new Promise((resolve, reject) => {
    if (options.needLogin && (!token || token.length <= 0)) {
      if (isRefreshing) {
        getToken();
        isRefreshing = false;
        pendings.push(() => {
          resolve(request({
            method,
            url,
            data,
            options
          }))
        })
      }
      return
    }
    wx.request({
      url: baseUrl + url,
      method: method || 'GET',
      data: data,
      header: {
        'content-type': 'application/json',
        ...myHeader
      },
      success: (res) => {
        if (res.statusCode == 200) {
          resolve(res.data)
          return
        }
        if (res.statusCode == 401) {
          if (isRefreshing) {
            getToken();
            isRefreshing = false;
            pendings.push(() => {
              resolve(request({
                method,
                url,
                data,
                options
              }))
            })
          }
        }
      },
      fail: (err) => {
        isRefreshing = true;
        reject(err)
      },
    })
  })
}

// 登录获取token
function getToken() {
  wx.login({
    success: (res) => {
      wx.request({
        url: baseUrl + '/mini/api/mine/login',
        method: 'POST',
        data: {
          code: res.code
        },
        success: (res) => {
          if (
            res.statusCode == 200 &&
            res.data.code == 200
          ) {
            wx.setStorageSync('token', res.data.data.token)
            app.globalData.userInfo = res.data.data.user.extParam
            pendings.map((callback) => {
              callback();
            })
            isRefreshing = true;
          } else {
            pendings = []
            wx.showToast({
              title: '登录失败请重试',
              icon: 'none'
            })
            isRefreshing = true;
            wx.switchTab({
              url: '/pages/square/square',
            })
          }
        },
        fail: (err) => {
          pendings = []
          wx.showToast({
            title: '登录失败请重试',
            icon: 'none'
          })
          isRefreshing = true;
          wx.switchTab({
            url: '/pages/square/square',
          })
        }
      })
    }
  })
}

module.exports = {
  request
};